package cn.z2huo.usercenter.authentication.app.controller.login.test;

import cn.z2huo.usercenter.authentication.model.vo.login.test.UserLoginReqVO;
import cn.z2huo.usercenter.util.RedisKeyGenerateUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * @author z2huo
 */
@RestController
@RequestMapping("/login")
@RequiredArgsConstructor
@Slf4j
public class LoginLimitController {

    private final RedissonClient redissonClient;

    private static final int LIMIT_COUNT = 5;

    private static final Duration LIMIT_TIME_DURATION = Duration.ofSeconds(60);

    @PostMapping("")
    public String login(@RequestBody UserLoginReqVO reqVO) throws InterruptedException {
        TimeUnit.MILLISECONDS.sleep(100);
        log.info("user login success");
        return "success";
    }

    @PostMapping("/fixed")
    public void loginLimitFixedWindow(@RequestBody UserLoginReqVO reqVO) throws InterruptedException {

        String redisKey = RedisKeyGenerateUtils.AUTHENTICATION_APP.generateMd5("user-login-fixed", reqVO.getUserCode());

        RAtomicLong atomicLong = redissonClient.getAtomicLong(redisKey);
        long count = atomicLong.getAndIncrement();
        if (count == 1) {
            atomicLong.expire(LIMIT_TIME_DURATION);
        }
        if (count >= LIMIT_COUNT) {
            throw new RuntimeException("限制时间内登陆次数过多，请稍后再试");
        }

        TimeUnit.MILLISECONDS.sleep(500);
        log.info("user login success");
    }

    @PostMapping("/sliding")
    public void loginLimitSlidingWindow() {

    }

    @PostMapping("/tokenBucket")
    public void loginLimitTokenBucket() {

    }


}
